package com.example.backend.service;

import com.example.backend.common.utils.IpUtils;
import com.example.backend.common.utils.UserAgentUtil;
import com.example.backend.dto.OnlineUser;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import jakarta.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 在线用户服务
 */
@Service
@RequiredArgsConstructor
public class OnlineUserService {
    
    private final RedisTemplate<String, OnlineUser> redisTemplate;
    private static final String ONLINE_USER_KEY = "online:user:";
    
    /**
     * 记录在线用户
     */
    public void recordOnlineUser(String token, Long userId, String username, HttpServletRequest request) {
        // 获取用户代理信息
        String userAgent = request.getHeader("User-Agent");
        UserAgent agent = UserAgent.parseUserAgentString(userAgent);
        
        // 获取IP和地理位置
        String ip = IpUtils.getIpAddr();
        String location = IpUtils.getLocation(ip);
        
        // 构建在线用户信息
        OnlineUser onlineUser = OnlineUser.builder()
                .token(token)
                .userId(userId)
                .username(username)
                .ip(ip)
                .location(location)
                .browser(UserAgentUtil.getBrowser(agent))
                .os(UserAgentUtil.getOS(agent))
                .loginTime(LocalDateTime.now())
                .build();
        
        // 存储到Redis，设置24小时过期
        String key = ONLINE_USER_KEY + token;
        redisTemplate.opsForValue().set(key, onlineUser, 24, TimeUnit.HOURS);
    }
    
    /**
     * 获取在线用户列表
     */
    public List<OnlineUser> getOnlineUsers() {
        Set<String> keys = redisTemplate.keys(ONLINE_USER_KEY + "*");
        if (keys == null || keys.isEmpty()) {
            return new ArrayList<>();
        }
        return redisTemplate.opsForValue().multiGet(keys);
    }
    
    /**
     * 强制下线
     */
    public void forceLogout(String token) {
        String key = ONLINE_USER_KEY + token;
        redisTemplate.delete(key);
    }
    
    /**
     * 用户注销
     */
    public void logout(String token) {
        String key = ONLINE_USER_KEY + token;
        redisTemplate.delete(key);
    }
} 